<script lang="ts">
	import { Any } from '$lib/api/proto/google/protobuf/any';
	import { RESOURCE_TYPE, type ResourceInfo } from '$lib/api/proto/resource_api';
	import type { NodeInfo } from '$lib/api/proto/roadmap_data_api';
	import { InnerResourceData } from '$lib/api/proto/roadmap_data_type_api';
	import { appStore } from '$lib/stores/app.svelte';
	import { userStore } from '$lib/stores/user.svelte';
	import { callApi } from '$lib/utils/call_utils';
	import { roadmapStore } from '../store.svelte';

	const PAGE_SIZE = 10;

	interface Props {
		node?: NodeInfo;
	}

	const props: Props = $props();

	let resourceId = $state(null as string | null);
	let resourceName = $state(null as string | null);
	let resourceType = $state(null as number | null);

	let resourceList = $state([] as ResourceInfo[]);
	let totalCount = $state(0);
	let curPage = $state(0);

	const pageCount = $derived(Math.ceil(totalCount / PAGE_SIZE));

	if (props.node != undefined && props.node.content != undefined) {
		const nodeContent = Any.unpack(props.node.content, InnerResourceData);
		resourceId = nodeContent.resourceId;
		resourceType = nodeContent.resourceType;
	}

	async function loadResourceList() {
		if (userStore.userSession == null) {
			return;
		}
		const res = await callApi(
			appStore.resourceApiClient.list({
				sessionId: userStore.userSession,
				filterByResourceType: props.node != undefined,
				resourceType: resourceType ?? RESOURCE_TYPE.RESOURCE_TYPE_CARD,
				filterByKeyword: false,
				keyword: '',
				offset: PAGE_SIZE * curPage,
				limit: PAGE_SIZE
			}).response
		);
		totalCount = res.totalCount;
		resourceList = res.resourceList;
	}

	function closeModal() {
		roadmapStore.targetNodeType = null;
		roadmapStore.targetDropPosition = null;
		roadmapStore.editNodeType = null;
		roadmapStore.editNode = null;
	}

	async function createNode() {
		if (
			roadmapStore.targetDropPosition == null ||
			userStore.userSession == null ||
			resourceId == null ||
			resourceName == null ||
			resourceType == null
		) {
			return;
		}

		const res = await callApi(
			appStore.roadmapDataApiClient.addNode({
				sessionId: userStore.userSession,
				roadmapId: roadmapStore.roadmapId,
				x: roadmapStore.targetDropPosition.x,
				y: roadmapStore.targetDropPosition.y,
				w: 300,
				h: 200,
				content: Any.pack(
					{
						resourceId: resourceId,
						resourceName: resourceName,
						resourceType: resourceType
					},
					InnerResourceData
				)
			}).response
		);
		roadmapStore.onUpdateNode(res.nodeId);
		appStore.addToastMessage({
			level: 'success',
			content: '创建资料库节点成功',
			keepTime: 2000
		});
		closeModal();
	}

	async function updateNode() {
		if (
			props.node == null ||
			userStore.userSession == null ||
			resourceId == null ||
			resourceName == null ||
			resourceType == null
		) {
			return;
		}

		await callApi(
			appStore.roadmapDataApiClient.updateNodeData({
				sessionId: userStore.userSession,
				roadmapId: roadmapStore.roadmapId,
				nodeId: props.node.nodeId,
				content: Any.pack(
					{
						resourceId: resourceId,
						resourceName: resourceName,
						resourceType: resourceType
					},
					InnerResourceData
				)
			}).response
		);
		roadmapStore.onUpdateNode(props.node.nodeId);
		appStore.addToastMessage({
			level: 'success',
			content: '修改资料库节点成功',
			keepTime: 2000
		});
		closeModal();
	}

	$effect(() => {
		loadResourceList();
	});
</script>

<dialog class="modal modal-open">
	<div class="modal-box">
		<button
			class="btn btn-sm btn-circle btn-ghost absolute right-2 top-2"
			onclick={() => closeModal()}>✕</button
		>
		<h3 class="text-lg font-bold">
			{props.node == undefined ? '创建资料库节点' : '修改资料库节点'}
		</h3>
		<div class="max-h-[60vh] overflow-y-auto pr-[10px] flex-col space-y-4 pt-[20px]">
			{#each resourceList as resource}
				<div class="flex gap-2 overflow-hidden truncate">
					<input
						type="radio"
						name="resource"
						class="radio"
						checked={resource.resourceId == resourceId}
						onchange={(e) => {
							if (e.currentTarget.checked) {
								resourceId = resource.resourceId;
								resourceName = resource.basicInfo?.name ?? '';
								resourceType = resource.resourceType;
							}
						}}
					/>
					{#if resource.resourceType == RESOURCE_TYPE.RESOURCE_TYPE_CARD}
						知识卡片
					{:else if resource.resourceType == RESOURCE_TYPE.RESOURCE_TYPE_EXAM}
						试题
					{/if}
					{resource.basicInfo?.name}
				</div>
			{/each}
		</div>
		{#if pageCount > 1}
			<div class="join bg-base-200 absolute right-[20px]">
				{#if curPage != 0}
					<button
						class="join-item btn btn-sm {curPage == 0 ? 'btn-active' : ''}"
						onclick={() => (curPage = 0)}>1</button
					>
				{/if}
				{#if pageCount > 3 && curPage > 1}
					<button class="join-item btn btn-sm btn-disabled">...</button>
				{/if}
				{#if curPage < pageCount}
					<button class="join-item btn btn-sm btn-active">{curPage + 1}</button>
				{/if}
				{#if curPage + 1 < pageCount}
					<button class="join-item btn btn-sm" onclick={() => (curPage += 1)}>{curPage + 2}</button>
				{/if}
				{#if pageCount - curPage > 4}
					<button class="join-item btn btn-sm btn-disabled">...</button>
				{/if}
				{#if pageCount - curPage > 3}
					<button class="join-item btn btn-sm" onclick={() => (curPage = pageCount - 2)}
						>{pageCount - 1}</button
					>
				{/if}
				{#if pageCount - curPage > 2}
					<button class="join-item btn btn-sm" onclick={() => (curPage = pageCount - 1)}
						>{pageCount}</button
					>
				{/if}
			</div>
		{/if}
		<div class="modal-action mt-[50px]">
			<button class="btn" onclick={() => closeModal()}>取消</button>
			<button
				class="btn btn-primary"
				disabled={resourceId == null}
				onclick={() => {
					if (props.node == undefined) {
						createNode();
					} else {
						updateNode();
					}
				}}>{props.node == undefined ? '创建' : '修改'}</button
			>
		</div>
	</div>
	<div class="modal-backdrop">
		<button onclick={() => closeModal()}>close</button>
	</div>
</dialog>
